import 'package:family_expense/features/account_user/models/join_account_group_request.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

/// The service communicates with backend for [User] usage.
class JoinAccountGroupRequestService {
  final String _url = '/join-account-group-request';
  final HttpRequestService _httpRequestService = HttpRequestService();

  /// Retrieves count of requests sent to current account group user.
  Future<int> countReceived() async {
    // Gets the response of the http get request.
    final response = await _httpRequestService.get('$_url/count-received');

    // Parses the data from [Map<String, dynamic>] to [User].
    return response.payload['count'] as int;
  }

  /// Retrieves current account group users from backend service.
  Future<List<JoinAccountGroupRequest>> queryReceiving(
      int pageSize, int pageIndex) async {
    // Gets the response of the http get request.
    final response = await _httpRequestService.get('$_url/query-receiving',
        params: {'pageSize': pageSize, 'pageIndex': pageIndex});

    // Parses the data from [Map<String, dynamic>] to [User].
    return (response.payload as List<dynamic>)
        .map((p) => JoinAccountGroupRequest.fromJson(p))
        .toList();
  }

  /// Sends a invitation request to [user].
  Future<bool> send(User user) async {
    final response = await _httpRequestService.post('$_url/send', body: {
      'receiverId': user.id,
      'roles': user.fullRoles!.map((e) => e.id).toList(),
    });

    return response.success;
  }

  /// Accepts a new invitation request by id.
  Future<bool> accept(String id) async {
    final response =
        await _httpRequestService.post('$_url/accept', body: {'id': id});

    return response.success;
  }

  /// Rejects a new invitation request by id.
  Future<bool> reject(String id) async {
    final response =
        await _httpRequestService.post('$_url/reject', body: {'id': id});

    return response.success;
  }

  /// Deletes a new invitation request by id.
  Future<bool> delete(String id) async {
    final response =
        await _httpRequestService.post('$_url/delete', body: {'id': id});

    return response.success;
  }
}
